// Msg.cpp

#include "stdafx.h"
#include "Socket.h"
#include "Utility.h"
#include "Msg.h"

#pragma warning(disable:4996)

static SimpleRand g_xRand;
static IPAddr g_xLocalAddr;

Msg::Msg()
{
	m_iMsgID=0;
	m_iSenderIP=0;
	memset(m_sText,0,sizeof(m_sText));
	memset(m_aiHistory,0,sizeof(m_aiHistory));
};

Msg::Msg(const Msg& p_xM)
{
	memcpy(this,&p_xM,sizeof(Msg));
};

Msg& Msg::operator=(const Msg& p_xM)
{
	memcpy(this,&p_xM,sizeof(Msg));
	return *this;
};

int Msg::GetLocalSenderIP()
{
	if(!g_xLocalAddr.IsValid())
	{
		g_xLocalAddr=IPAddr::GetLocalDefault();
	};
	return g_xLocalAddr.GetHost();
};

void Msg::Init(const char* p_sText)
{
	m_iMsgID=g_xRand.Rand()|(g_xRand.Rand()<<15);
	strncpy(m_sText,p_sText,MAX_TEXT);
	m_sText[MAX_TEXT-1]='\0';
	if(!g_xLocalAddr.IsValid())
	{
		g_xLocalAddr=IPAddr::GetLocalDefault();
	};
	m_iSenderIP=g_xLocalAddr.GetHost();
};

void Msg::Print() const
{
	printf("%d.%d.%d.%d:%d %s\n",
		(m_iSenderIP)&0xff,
		(m_iSenderIP>>8)&0xff,
		(m_iSenderIP>>16)&0xff,
		(m_iSenderIP>>24)&0xff,
		m_iMsgID,m_sText);
};

bool Msg::AddHistory(int p_iIP)
{
	int i;
	for(i=0;i<MAX_HISTORY;i++)
	{
		if(m_aiHistory[i]==p_iIP)
		{
			return false;
		}
		else if(m_aiHistory[i]==0)
		{
			m_aiHistory[i]=p_iIP;
			return true;
		};
	};
	return false;
};

bool Msg::IsInHistory(int p_iIP) const
{
	int i;
	for(i=0;i<MAX_HISTORY;i++)
	{
		if(m_aiHistory[i]==p_iIP)
		{
			return true;
		};
	};
	return false;
};

